﻿using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Globalization;

namespace HP48CSharp.Core
{
    internal abstract class CSharpCompilerCore
    {

        public string Template { get; set; }
        public string Function { get; set; }

        private string code;

        internal CSharpCompilerCore()
        {}

        internal CSharpCompilerCore( string function)
        {
            Function = function;
        }

        internal object CompileExecutable()
        {
            CSharpCodeProvider codeprovider = new CSharpCodeProvider();

            code = string.Format(new CultureInfo("en-US"), Template, this.Function);

            CompilerResults results =
                codeprovider.CompileAssemblyFromSource(new CompilerParameters(), code);

            if (results.Errors.Count != 0)
                Console.WriteLine("Error");

            Type mainType = results.CompiledAssembly.GetType("Calculator");
            MethodInfo mainMethod = mainType.GetMethod("Execute");

            return mainMethod.Invoke(null, null);
        }
    }
}
